import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Logger;



/**
 * Created by lucas on 2017/4/22.
 */
public class ProxyUtil {

    private static final Logger LOG = Logger.getLogger(ProxyUtil.class.getName());

    public Set<String> unavailableIP;

    private static final String xdailiURL = "http://www.xdaili.cn/ipagent/freeip/getFreeIps?page=1&rows=0";

    public ProxyUtil()
    {
        unavailableIP = new HashSet<String>();
    }

    public boolean isAvailable(String url, String proxy) {
        if (unavailableIP.contains(proxy)) return false;
        String ip = proxy.split("\t")[0];
        String port = proxy.split("\t")[1];
        String response = HttpRequestUtil.sendGetWithProxy(url, ip, port);
        if (response != null) {
            LOG.info("available ip:" + ip);
            return true;
        } else {
            LOG.info("unavailable ip:" + ip);
            unavailableIP.add(proxy);
            if (unavailableIP.size()>100) unavailableIP.clear();
            return false;
        }
    }

    public String getProxyFromXdaili(String url) {
        //讯代理十分钟更新一次
        LOG.info("getting proxy.....");
        ArrayList<String> result = new ArrayList<>();
        String response = HttpRequestUtil.sendGet(xdailiURL);
        JSONObject jsonObject = new JSONObject(response);
        JSONArray rows = jsonObject.getJSONArray("rows");
        for (int i = 0; i < rows.length(); i++) {
            JSONObject ipJson = rows.getJSONObject(i);
            String ip = ipJson.getString("ip");
            String port = ipJson.getString("port");
            String proxy = ip + '\t' + port;
            if (isAvailable(url, proxy)) return proxy;
        }
        return null;
    }

    public static void main(String args[]) {
    }
}
